<template>
  <div class="editdiv">

    <div class="headbtn_box">
      <div class="addbutton">
        <el-button size="small" type="warning"  icon="el-icon-close" class="text-two" @click="handleClose">关闭</el-button>
        <el-button type="primary" size="small"  icon="el-icon-check" class="text-two" @click="submitHandler">保存</el-button>
      </div>
    </div>

     <div class="container">
       <el-form :model="form" label-position="left" size="small" ref="form" label-width="120px">

          <div  class="form_input_box">


               <el-card class="box-card">
                 <div slot="header" class="clearfix">
                   <span>车辆基础信息</span>
                 </div>

                <el-row :gutter="10">



                  <el-col :span="8">
                      <el-form-item label="所属门店" prop="deptId" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                       <el-select v-model="form.deptId" placeholder="所属门店" clearable>
                         <el-option
                           v-for="item in storeList"
                           :key="item.deptId"
                           :label="item.deptName"
                           :value="item.deptId"
                         />
                       </el-select>
                      </el-form-item>
                  </el-col>

                  <el-col :span="8">
                      <el-form-item label="车型" prop="modelId" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                       <el-select v-model="form.modelId" placeholder="车型" >
                         <el-option
                           v-for="item in carModelList"
                           :key="item.id"
                           :label="item.name"
                           :value="item.id"
                         />
                       </el-select>
                      </el-form-item>
                  </el-col>



                  <el-col :span="8">
                        <el-form-item label="车牌号" prop="carNo" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                            <CarPlant  ref="carPlantDom"  :item="form.carNo" @carback="carNoCallback"></CarPlant>
                            <input type="hidden" v-model="form.carNo">
                        </el-form-item>

                  </el-col>


                  <el-col :span="8">
                    <el-form-item   label="汽车品牌" prop="brand"  :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                      <el-input v-model="form.brand" placeholder="汽车品牌"  />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item label="新能源" prop="newEnergyVehicles" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                      <el-select v-model="form.newEnergyVehicles" placeholder="新能源" >
                        <el-option
                          v-for="dict in dict.type.new_energy_vehicles"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>


                  <el-col :span="8">
                    <el-form-item label="客户信息" prop="customerId" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                         <CustomerTag :item="{'id':form.customerId,'name':form.customerName}"  ref="customerDom" @callback="customerCallback"></CustomerTag>
                         <input type="hidden" v-model="form.customerId">
                    </el-form-item>

                  </el-col>


                  <el-col :span="8">
                    <el-form-item   label="联系人姓名" prop="contactName"  :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                      <el-input v-model="form.contactName" placeholder="联系人姓名"  />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item   label="联系电话" prop="contactPhone"  :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                      <el-input v-model="form.contactPhone" placeholder="联系电话"  />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item   label="车架号" prop="vin"  >
                      <el-input v-model="form.vin" placeholder="车架号"  />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item   label="发动机编号" prop="engineNo" >
                      <el-input v-model="form.engineNo" placeholder="发动机编号"  />
                    </el-form-item>
                  </el-col>


                  <el-col :span="8">
                    <el-form-item   label="到店里程数" prop="arrivalMileage"  :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                      <el-input v-model="form.arrivalMileage" placeholder="到店里程数"  />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item   label="下次保养程数" prop="nextMileage"  :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                      <el-input v-model="form.nextMileage" placeholder="下次保养程数"  />
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item   label="年检时间" prop="inspectionDate" >
                      <el-date-picker
                           v-model="form.inspectionDate"
                           type="date"
                           value-format="yyyy-MM-dd"
                           placeholder="选择日期">
                         </el-date-picker>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item   label="保险到期时间" prop="insuranceDate" >
                      <el-date-picker
                           v-model="form.insuranceDate"
                           type="date"
                           value-format="yyyy-MM-dd"
                           placeholder="选择日期">
                         </el-date-picker>
                    </el-form-item>
                  </el-col>

                  <el-col :span="8">
                    <el-form-item   label="保险公司" prop="insuranceCompany"  >
                      <el-input v-model="form.insuranceCompany" placeholder="保险公司"  />
                    </el-form-item>
                  </el-col>

                  <el-col :span="24">
                    <el-form-item   label="备注" prop="remark"  >
                      <el-input v-model="form.remark"  type="textarea" :rows="2"   />
                    </el-form-item>
                  </el-col>



                </el-row>



               </el-card>


               <el-card class="box-card">
                 <div slot="header" class="clearfix">
                   <span>车辆属性</span>
                 </div>
                 <div  class="text item">
                    <div style="margin-top: 20px">
                       <el-button @click="addProps()">添加属性</el-button>
                     </div>


                        <el-table class="mytable" :data="form.attributesList"  border  style="width: 100%">
                           <el-table-column    label="属性名称"  align="left" width="280px">
                             <template slot-scope="scope" >
                                 <el-form-item label-width="0px" :prop="'attributesList.' + scope.$index + '.key'"  :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                                   <el-input v-model="scope.row.key"></el-input>
                                 </el-form-item>
                             </template>

                           </el-table-column>
                           <el-table-column   label="属性值" align="left" >
                             <template slot-scope="scope" >
                                 <el-form-item label-width="0px" :prop="'attributesList.' + scope.$index + '.value'" :rules="[{ required: true, message: '该值不能为空', trigger: 'blur' }]">
                                   <el-input v-model="scope.row.value"></el-input>
                                 </el-form-item>
                             </template>
                           </el-table-column>

                           <el-table-column label="操作" width="200px">
                             <template slot-scope="scope">
                               <el-button  size="mini" type="danger"  @click="removeProps(scope.$index)">删除</el-button>
                             </template>
                           </el-table-column>
                         </el-table>


                      <el-button @click="addProps()">添加属性</el-button>

                 </div>
               </el-card>

               <el-card class="box-card">
                 <div slot="header" class="clearfix">
                   <span>车辆照片</span>
                 </div>
                 <div  class="text item">
                   <el-upload
                       :action="imageUploadUrl"
                       :headers="headers"
                       list-type="picture-card"
                       :limit='9'
                       :file-list="form.carInfoPhotoList"
                       :before-upload="beforeAvatarUpload"
                       :on-success="handleAvatarSuccess"
                       :on-preview="handlePictureCardPreview"
                       :on-remove="handleRemove"
                       >
                       <i class="el-icon-plus"></i>
                    </el-upload>
                      <!-- 图片放大显示 -->
                      <el-dialog :visible.sync="dialogVisible">
                          <img width="100%" :src="dialogImageUrl" alt="">
                     </el-dialog>

                 </div>
               </el-card>

             </div>


        </el-form>


     </div>





  </div>
</template>

<script>
  import CarPlant from '@/components/CarPlant/index.vue'
  import CustomerTag from '@/components/CustomerTag/index.vue'
  import {allStore} from '@/api/system/dept.js'
  import {dataApi as carModelApi} from '@/api/car/model.js'
  import {removePhotoById, addApi, findByIdApi, editApi} from '@/api/info/carinfo.js'
  import { getToken } from '@/utils/auth'
  export default {
    // 查询通用字典中的键
    dicts: ['customer_class','new_energy_vehicles'],
    components:{
      CarPlant,
      CustomerTag
    },
    computed: {
        headers() {
          return {'Authorization': 'Bearer '+ getToken() }
        }
    },
    data(){
      return {
        //所属门店
        storeList:[],
        //车型
        carModelList:[],
        form: {
          attributesList: [],
          carInfoPhotoList: []
        },
        dialogVisible:false,
        dialogImageUrl:'',
        // 头像上传url
        imageUploadUrl: process.env.VUE_APP_BASE_API+'/api/upload/image',
      }
    },
    created(){
      const id = this.$route.query && this.$route.query.id;
      //加载数据
      this.fetchAllData()

      // 修改
      if (id) {
        findByIdApi(id).then(resp=> {
          this.form= resp.data
        })
      }
    },
    methods:{
      // 返回按钮
      handleClose() {
        const obj = { path: "/info/car" };
        this.$tab.closeOpenPage(obj);
      },
      //输入完毕车牌号回调
      carNoCallback(obj){
        console.log(obj)
        this.$set(this.form, 'province', obj.province)
        this.$set(this.form, 'carNo', obj.value)
      },
      // 加载数据
      fetchAllData(){
        //查询所有门店
        allStore().then(resp => {
          this.storeList = resp.data
        })
        //车型
        carModelApi({'page':1,'size':100}).then(resp=> {
           this.carModelList = resp.rows
        })
      },
      //选择客户回调
      customerCallback(row){
        console.log(row)
        // 响应式变量
        this.$set(this.form, 'customerId', row.id)
        this.$set(this.form, 'contactName', row.name)
        this.$set(this.form, 'contactPhone', row.phone)
      },

      //移出属性
      removeProps(index){
        console.log(index)
        this.form.attributesList.splice(index,1)
      },
      //新装置属性
      addProps(){
        const item= {'key': undefined, 'value': undefined}
        this.form.attributesList.push(item)
      },
      //保存按钮
      submitHandler(){
            this.$refs['form'].validate((valid) => {
                  if (valid) {
                    // 修改操作
                        if(this.form.id){
                          // this.editSave()
                          this.editSave()
                        }else{
                          //新增操作
                          this.addSave()
                        }
                  } else {
                    console.log('error submit!!');
                    return false;
                  }
             });
      },
      //这是我们点击移除时的函数
      handleRemove(file, fileList) {

        if(file.id){

          let  index=-1;
          //移出后台数据库的值 delete from car_info_photo where id=?
          for(let i=0;i<this.form.carInfoPhotoList.length;i++){
             if(this.form.carInfoPhotoList[i].id === file.id){
               index=i;
               break;
             }
          }

           this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {

              //向数据发送一条删除操作语句
              removePhotoById(file.id).then(resp => {
                //移出前端的数据
                this.form.carInfoPhotoList.splice(index,1)
              })

            }).catch(() => {
                //还原数据
                fileList.splice(index,0,file)
            });

        }else{
          //临时数据
          let  index=-1;
          for(let i=0;i<this.form.carInfoPhotoList.length;i++){
             if(this.form.carInfoPhotoList[i].uid=== file.uid){
               index=i;
               break;
             }
          }

          this.$confirm('此操作将永久删除该图片, 是否继续?', '提示', {
             confirmButtonText: '确定',
             cancelButtonText: '取消',
             type: 'warning'
           }).then(() => {
               this.form.carInfoPhotoList.splice(index,1)
           }).catch(() => {
               //还原数据
               fileList.splice(index,0,file)
           }); 
        }
      },
      //预览图片
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      // 验证图片格式
      beforeAvatarUpload(file) {
        const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isImage) {
          this.$message.error('上传头像图片只能是 JPG 和 PNG格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isImage && isLt2M;
      },
      // 图片上传成功的时候
       handleAvatarSuccess(res, file) {
         //[{name: 'food.jpg', url: 'https://xxx.cdn.com/xxx.jpg'}]
         if(res.code===200){
           const obj={
             'name': res.data.file_name,
             'url': res.data.image_url
           }
            this.form.carInfoPhotoList.push(obj)
         }
       },
       // 新增保存
       addSave(){
         addApi(this.form).then(resp=> {
           this.$confirm('操作成功，是否继续添加车辆信息?', '提示', {
               confirmButtonText: '继续添加',
               cancelButtonText: '取消',
               type: 'warning'
             }).then(() => {
               // 清空表单的值
               this.form = {
                    attributesList: [],
                    carInfoPhotoList: []
                }
                //清空车牌号
                this.$refs['carPlantDom'].clearForm()
                //清空客户信息
                this.$refs['customerDom'].clearForm()

             }).catch(() => {
                this.handleClose()
             });
         })
       },
       //修改保存
      editSave(){
        editApi(this.form).then(resp=> {
          this.$message('操作成功');
          this.handleClose()
        })
      }

    }
  }
</script>

<style scoped="scoped" lang="scss">

  .editdiv {
      height: 100%;

      .headbtn_box {
          position: relative;
          background-color: white;
          height: 64px;
          display: flex;
          align-items: center;
          justify-content: flex-end;
          padding: 0 16px;
          width: 100%;
          z-index: 1;
          min-width: 950px;
          box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.05);

          .addbutton {
              right: 10px;

              >>> button {
                  margin: 0 8px;
              }
          }
      }



      .container {
          height: calc(100% - 64px);
          padding: 15px;

          .box-card{
            margin-bottom: 20px;
          }
      }


      .box_tit {
          font-size: 16px;
          font-weight: bold;
          color: #000000;

      }





      .search_icon {
          position: absolute;
          right: 10px;
          top: 0;
          font-size: 18px;
          color: #b7b7b7;
          cursor: pointer;
      }

      .map_box {
          display: flex;
          height: 600px;



          #container {
              flex: 1;
              height: 100%;
          }
      }
  }



</style>
